# Author    :Dun_Hz
# Time      :2024/3/13 15:49
# 24点游戏，数字范围1~13
from __future__ import division
from itertools import combinations
import re

class Solver:
    # 设置最终结果
    target = 24
    # 定义四则运算符
    # 其中 a -- b = b-a, a//b = b/a
    ops = ['+', '-', '*', '/', '--', '//']
    #precise_mode 为精准模式，若开启，则减号及除号后面自动开启括号
    def __init__(self, precise_mode = False):
        self.precise_mode = precise_mode

    def solution(self, nums):
        result = []

    def dimensionality_reduction(self, nums):
        # 降维，对多种组合不断降维处理
        result = []
        # 如果维数大于2，则选出两个表达式组合成一个，降低一个维度
        if len(nums)>2:
            for group in self.group(nums, 2):
                for op in self.ops:
                    new_group = [self.assemble(group[0][0],group[0][1],op)]
                    result = self.dimensionality_reduction(new_group)
        else:
            result = [nums]
        return result


    # 将两个表达式组合成一个新表达式
    def assemble(self,exp1,exp2,op):
        if op =='--' or op =='//':
            return self.assemble(exp2, exp1, op[0])
        if op in r'/*':
            exp1 = self.add_parenthesis(exp1)
            exp2 = self.add_parenthesis(exp2)
        if self.precise_mode:
            if op =='-':
                exp2 = self.add_parenthesis(exp2)
            elif op == '/':
                exp2 = self.add_parenthesis(exp2, True)
        exp = self.convert

    @staticmethod
    def add_parenthesis(exp, is_necessary = False):
        #如果上一步计算步骤为加号或减号，则加括号
        if (is_necessary and not exp['exp'].isdigit()) or exp['op'] in r'+-':
            result = {
                'exp':'('+exp['exp']+')',
                'op':exp['op']
            }
        else:
            result = exp
        return result

    @staticmethod
    def check(exp, target, precision = 1e-6):
        try:
            return abs(eval(exp) - target) < 1e-6
        except ZeroDivisionError:
            return "You can't divide by zero"

    # 将表达式排序为等价标准表达式
    @staticmethod
    def convert(exp,op):
        if op in '+-':
            pattern = ''

    @staticmethod
    def format(nums):
        # 将输入的数字格式化为字典，运算符号为空格
        return [{'op': ' ', 'exp':str(num)} for num in nums]


    def group(self, exp_list, counter):
        '''
        对表达式列表进行分组：
        [[[n1,n2],[n3,n4]],
         [[n1,n3],[n2,n4]],
         [[n1,n4],[n2,n3]]]
        '''
        # 列表：元素是下标号
        index_list = [i for i in range(len(exp_list))]
        # 通过对元素标号排列组合取值
        combination = list(combinations(index_list,counter))
        for group1 in combination:
            group2 = list(set(index_list) - set(group1))
            yield [
                [exp_list[g1] for g1 in group1],
                [exp_list[g2] for g2 in group2]
            ]

